package casa.depesos.app.com.frag;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.SPHelper;
import com.google.gson.Gson;
import com.support.toast.ToastUtil;

import casa.depesos.app.com.App;
import casa.depesos.app.com.R;
import casa.depesos.app.com.activity.LoginActivity;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.databinding.FragmentCodeLoginBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.ReadDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.CodeLoginBean;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.bean.WhiteDataBean;
import casa.depesos.app.com.http.data.CodeType;
import casa.depesos.app.com.http.data.Usr;
import casa.depesos.app.com.http.req.CheckCodeReq;
import casa.depesos.app.com.http.req.CodeLoginReq;
import casa.depesos.app.com.http.req.GetWhiteReq;
import casa.depesos.app.com.http.req.no.SloganReq;
import casa.depesos.app.com.utils.Captcha;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class CodeFragment extends SmsBaseFragment {
    FragmentCodeLoginBinding binding;
    boolean hasRight, isRegistered;
    int way;
    String phone;

    public void setParam(boolean hasRight, int way, String phone, boolean isRegistered) {
        this.hasRight = hasRight;
        this.way = way;
        this.phone = phone;
        this.isRegistered = isRegistered;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isRegistered) {
            Report.show("ACTION_DD_001");
        } else {
            Report.show("ACTION_GG_001");
        }
        new SloganReq().req();
    }

    private Captcha mCaptcha;

    private Bitmap getBmCode() {
        if (mCaptcha == null) {
            mCaptcha = Captcha.getInstance()
                    .setType(Captcha.TYPE.CHARS)
                    .setSize(Utils.dp2Px(getActivity(), 70), Utils.dp2Px(getActivity(), 35))
                    .setBackgroundColor(0xfff0f0f0)
                    .setLength(4)
                    .setLineNumber(2)
                    .setFontSize(50)
                    .setFontPadding(20, 20, 45, 15);
        }
        return mCaptcha.create();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentCodeLoginBinding.inflate(inflater, container, false);
        binding.getRoot().setPadding(0, Utils.getStatusBarHeight(getActivity()), 0, 0);

        binding.back.setOnClickListener(view -> ((LoginActivity) getActivity()).removeFragment(this));

        binding.check.setText(getString(R.string.check0) + getString(R.string.check1));
        Utils.setClickableText(binding.check, Constant.PRIVACY, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isRegistered) {
                    Report.click("ACTION_GG_003");
                }
            }
        });
        if (isRegistered) {
            binding.bottom.setVisibility(View.VISIBLE);
            binding.way.setOnClickListener(v -> ((LoginActivity) getActivity()).changeWay(phone));
            if (way == 0) {
                binding.way.setImageResource(R.mipmap.lock);
            } else {
                binding.way.setImageResource(R.mipmap.sms);
            }
        } else {
            binding.bottom.setVisibility(View.INVISIBLE);
        }
        if (Constant.white) {
            binding.linear.setVisibility(View.VISIBLE);
            binding.frame.setVisibility(View.GONE);
            binding.code.setImageBitmap(getBmCode());
            binding.pwd2.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    int len = s.toString().length();
                    if (len > 0) {
                        binding.clear2.setVisibility(View.VISIBLE);
                    } else {
                        binding.clear2.setVisibility(View.GONE);
                    }
                    boolean bo = len == 4;
                    binding.next.setEnabled(bo);
                    binding.next.setAlpha(bo ? 1 : 0.6f);
                }
            });
            Utils.setEditTextInputSpace(binding.pwd2, 4);

            binding.clear2.setOnClickListener(v -> binding.pwd2.setText(""));
            binding.refresh.setOnClickListener(v -> binding.code.setImageBitmap(getBmCode()));

        } else {
            binding.linear.setVisibility(View.GONE);
            binding.frame.setVisibility(View.VISIBLE);
            binding.pwd.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    int len = s.toString().length();
                    if (len > 0) {
                        binding.clear.setVisibility(View.VISIBLE);
                    } else {
                        binding.clear.setVisibility(View.INVISIBLE);
                    }
                    boolean bo = len == 6;
                    binding.next.setEnabled(bo);
                    binding.next.setAlpha(bo ? 1 : 0.6f);
                }
            });
            Utils.setEditTextInputSpace(binding.pwd, 6);

            binding.clear.setOnClickListener(v -> binding.pwd.setText(""));
            binding.get2.setOnClickListener(v -> getCode());
        }
        if (!isRegistered) {
            binding.next.setText("Registrar");
        }
        binding.next.setOnClickListener(v -> login());
        if (hasRight && !Constant.white) {
            getCode();
        }

        return binding.getRoot();
    }

    @Override
    protected void countDown() {
        super.countDown();
        binding.get2.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void timeOut() {
        binding.get2.setVisibility(View.VISIBLE);
    }

    private void login() {
        if (!binding.check.isChecked()) {
            if (!isRegistered) {
                Report.show("ACTION_GG_005");
            }
            new ReadDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        if (!isRegistered) {
                            Report.click("ACTION_GG_006");
                        }
                        binding.check.setChecked(true);
                        login2();
                    } else {
                        if (!isRegistered) {
                            Report.click("ACTION_GG_007");
                        }
                    }
                }
            }).show(getChildFragmentManager(), "");
        } else {
            login2();
        }
    }

    private void login2() {
        String code = binding.pwd.getText().toString().trim();
        if (code.length() != 6) {
            ToastUtil.showShortToast(getActivity(), "Código de verificación incorrecto, ingrese de nuevo");
        } else {
            showLoading();
            if (isRegistered) {
                Report.click("ACTION_DD_005");
            } else {
                Report.click("ACTION_GG_002");
            }
            if (isRegistered) {
                new CodeLoginReq(phone, code).req(new ReqCallback<CodeLoginBean>() {
                    @Override
                    public void callback(boolean success, CodeLoginBean bean) {
                        if (success && bean.isValid()) {
                            Report.show("ACTION_DD_007");
                            Report.adjustEvent("i6cysf");
                            Usr u = new Usr();
                            u.token = bean.data.token;
                            u.uid = bean.data.uid;
                            u.phone = phone;
                            u.isAdmin = bean.data.isAdmin;
                            if (u.isAdmin) {
                                new GetWhiteReq().req(new ReqCallback<WhiteDataBean>() {
                                    @Override
                                    public void callback(boolean success, WhiteDataBean bean) {
                                        hideLoading();
                                        if (success) {
                                            SPHelper.getInstance(App.getApp()).putStringAndCommit("usr", new Gson().toJson(u));
                                            Constant.white = true;
                                            jump();
                                        } else {
                                            ToastUtil.showShortToast(getActivity(), "Solicitud incorrecta");
                                        }
                                    }
                                });
                            } else {
                                SPHelper.getInstance(App.getApp()).putStringAndCommit("usr", new Gson().toJson(u));
                                jump();
                            }
                        } else {
                            hideLoading();
                        }
                    }

                    void jump() {
                        hideLoading();
                        Intent i = new Intent(getActivity(), MainActivity.class);
                        startActivity(i);
                        getActivity().finish();
                    }
                });
            } else {
                new CheckCodeReq(phone, code, CodeType.REGISTER).req(new ReqCallback<GetCodeBean>() {
                    @Override
                    public void callback(boolean success, GetCodeBean bean) {
                        hideLoading();
                        if (success && bean.isValid()) {
                            toPwd(code);
                        }
                    }
                });
            }
        }
    }

    private void toPwd(String code) {
        ((LoginActivity) getActivity()).toSetPwd(phone, code);
        ((LoginActivity) getActivity()).removeFragment(this);
    }

    @Override
    protected String getPhone() {
        return phone;
    }

    @Override
    protected CodeType getCodeType() {
        if (isRegistered) {
            return CodeType.LOGIN;
        }
        return CodeType.REGISTER;
    }

    @Override
    protected TextView getCodeTv() {
        return binding.get;
    }
}
